function addEvent(elem, type, handle) {
  if (elem.addEventListener) {
    elem.addEventListener(type, handle, false);
  } else if (elem.attachEvent) {
    elem.attachEvent('on' + type, function () {
      handle.call(elem);
    });
  } else {
    elem['on' + type] = handle;
  }
}

function removeEvent(elem, type, handle) {
  if (typeof elem.removeEventListener !== 'undefined') {
    elem.removeEventListener(type, handle, false);
  } else if (typeof elem.detachEvent !== 'undefined') {
    elem.detachEvent('on' + type);
  }
}

function debounce(fn, wait = 200, immediate) {
  let timer;
  return function () {
    if (timer) clearTimeout(timer);
    if (immediate) {
      timer = setTimeout(() => {
        timer = null;
      }, wait);
      if (!timer) {
        fn.apply(this, arguments);
      }
    } else {
      timer = setTimeout(() => {
        fn.apply(this, arguments);
      }, wait);
    }
  };
}

//节流(立即执行)
function throttle(fn, wait = 200) {
  let flag = true;
  let timer = null;
  return function () {
    if (flag) {
      fn.apply(this, arguments);
      flag = false;
      timer = setTimeout(() => {
        flag = true;
      }, wait);
    }
  };
}

export { addEvent, removeEvent, debounce, throttle };
